package com.amit.jsp;

import java.io.Writer;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class CountWordTag  extends BodyTagSupport{
	
	public CountWordTag()
	{
		
	}
	
	private String word;

	public void setWord(String word) {
		this.word = word;
	}
	
	@Override
	public int doStartTag() throws JspException {

		
		return EVAL_BODY_BUFFERED;
	}
	
	@Override
	public int doEndTag() throws JspException {
		
		String str=getBodyContent().getString();
		int count=countWord(str);
		try
		{
			Writer out=pageContext.getOut();
			out.write(str);
			out.write("<br/> Occuence of"+word+"is:"+count);
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return EVAL_PAGE;
	}

	private int countWord(String str) {
		
		int count=0;
		for(int i=0;i<str.length();i++)
		{
			int index=str.indexOf(word, i);
			if(index>=0)
			{
				count++;
				i=index+1;
			}
			System.out.println(i+"\t"+index);
		}
		return count;
	}

}
